package com.loto.insurance.framework.Air.CPIC;

import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.Date;

import javax.xml.rpc.ServiceException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.loto.insurance.framework.InsuranceStatusEnum;
import com.loto.insurance.framework.MsgStatusEnum;
import com.loto.insurance.framework.Air.InsAir;
import com.loto.insurance.framework.Air.InsReturnMsg;
import com.loto.insurance.framework.Air.OrderItemInfo;
import com.loto.insurance.framework.Air.PICC.PICCInsAir;
import com.loto.insurance.framework.config.CPICConfigAir;
import com.loto.insurance.framework.config.ConfigManagementAir;
import com.loto.utils.DateUtils;

public class CPICInsAir implements InsAir {
  static Logger logger = LogManager.getLogger(PICCInsAir.class);

  private static String SUCCESSFULLY_CODE = "S000";

  private String productCode;

  private CPICConfigAir cpicConfigAir;

  public CPICInsAir(String productCode) {
	this.productCode = productCode;
	this.cpicConfigAir = getCpicConfigAir();
  }

  @Override
  public InsReturnMsg PolicyApproval(OrderItemInfo info) {
	InsReturnMsg message = new InsReturnMsg();

	SoapBusinessInterServiceLocator sbic = new SoapBusinessInterServiceLocator();
	StandardApprovalResponse response = new StandardApprovalResponse();

	StandardApprovalRequest request = new StandardApprovalRequest();
	request.setOuterOrderID(info.getTransOrderNo());

	Insurance ins = new Insurance();
	ins.setProductCode(cpicConfigAir.getProductCode());
	// ins.policyBeginDate = TimeZoneInfo.ConvertTimeToUtc(info.FromPeriod);
	Calendar beginDate = Calendar.getInstance();
	beginDate.set(
	    DateUtils.getYear(DateUtils.dateToNormalString(info.getFromPeriod())),
	    DateUtils.getMonth(DateUtils.dateToNormalString(info.getFromPeriod())),
	    DateUtils.getDay(DateUtils.dateToNormalString(info.getFromPeriod())));
	ins.setPolicyBeginDate(beginDate);
	// ins.policyEndDate =
	// TimeZoneInfo.ConvertTimeToUtc(info.FromPeriod.AddDays(9));
	Calendar endDate = Calendar.getInstance();
	Date eDate = DateUtils.addDays(info.getFromPeriod(),
	    cpicConfigAir.getCycle());
	endDate.set(DateUtils.getYear(DateUtils.dateToNormalString(eDate)),
	    DateUtils.getMonth(DateUtils.dateToNormalString(eDate)),
	    DateUtils.getDay(DateUtils.dateToNormalString(eDate)));
	ins.setPolicyEndDate(endDate);
	ins.setPhoneNumber(info.getInsuredTel());
	ins.setFlightNo(info.getFlightNo());
	ins.setApplicantName(info.getHolderName());
	ins.setApplicantCertType(getCertificateType(info.getHolderCredentialType()));
	ins.setApplicantCercCode(info.getHolderCredentialNo());
	Calendar birthDate = Calendar.getInstance();
	Date bDate = info.getHolderBirth();
	birthDate.set(DateUtils.getYear(DateUtils.dateToNormalString(bDate)),
	    DateUtils.getMonth(DateUtils.dateToNormalString(bDate)),
	    DateUtils.getDay(DateUtils.dateToNormalString(bDate)));
	ins.setApplicantBirth(birthDate);
	ins.setApplicantSex(getGender(info.getHolderGender()));

	// ins.claimantName = info.HolderName;
	// ins.claimantCertType = GetCertificateType(info.HolderCredentialType);
	// ins.claimantCercCode = info.HolderCredentialNo;
	// ins.insurantNexus = "301";

	ins.setInsuredName(info.getInsuredName());
	ins.setInsuredCertType(getCertificateType(info.getInsuredCredentialType()));
	ins.setInsuredCercCode(info.getInsuredCredentialNo());

	Calendar insuredDate = Calendar.getInstance();
	Date iDate = info.getInsuredBirth();
	insuredDate.set(DateUtils.getYear(DateUtils.dateToNormalString(iDate)),
	    DateUtils.getMonth(DateUtils.dateToNormalString(iDate)),
	    DateUtils.getDay(DateUtils.dateToNormalString(iDate)));
	ins.setInsuredBirth(insuredDate);

	ins.setInsuredSex(getGender(info.getInsuredGender()));

	request.setUserInfo(getUserInfo());
	request.setInsuranceDetail(ins);

	logger.info("CPIC_Approval_Request:" + info.getInsuredName());

	try {
	  response = sbic.getSoapApplyBusiness().standardApproval(request);
	  logger.info("CPIC_Approval_Response:"
		  + response.getSysMessage().getNoteMsg());

	  message.setInsNo(response.getPolicyNo());
	  message.setInsTransNo(response.getBy2());
	  message.setMessage(response.getSysMessage().getNoteMsg()
		  + response.getSysMessage().getErrorMsg());

	  if (response.getSysMessage().getReturnNumber().equals(SUCCESSFULLY_CODE)
		  || !response.getPolicyNo().isEmpty()) {
		message.setStatus(MsgStatusEnum.SUCCESS);
		message.setInsStatus(InsuranceStatusEnum.EFFECT);
	  } else {
		message.setStatus(MsgStatusEnum.FAIL);
	  }
	} catch (Exception e) {
	  // TODO Auto-generated catch block
	  e.printStackTrace();
	  message.setStatus(MsgStatusEnum.FAIL);
	}

	return message;
  }

  @Override
  public InsReturnMsg PolicyQuery(OrderItemInfo info) {
	InsReturnMsg message = new InsReturnMsg();
	SoapBusinessInterServiceLocator sbic = new SoapBusinessInterServiceLocator();
	PolicyQueryRequest request = new PolicyQueryRequest();
	PolicyQueryResponse response = new PolicyQueryResponse();
	request.setInsuredCercCode(info.getInsuredCredentialNo());
	request.setInsuredCertType(getCertificateType(info
	    .getInsuredCredentialType()));
	request.setUserInfo(getUserInfo());
	request.setPolicyNo(info.getInsuranceNo());

	logger.info("CPIC_Query_Request:" + info.getInsuranceNo());

	// request.transID = "20002";
	// request.outerOrderId = info.TransOrderNo;
	try {
	  response = sbic.getSoapApplyBusiness().policyQuery(request);

	  logger.info("CPIC_Query_Response:"
		  + response.getSysMessage().getNoteMsg());

	  message.setMessage(response.getSysMessage().getErrorMsg());

	  SoapQueryPolicy insuranceDetail = response.getInsuranceDetail();
	  if (insuranceDetail != null) {
		message.setInsNo(insuranceDetail.getPolicyNo());
		message.setInsTransNo(insuranceDetail.getBillNo());
		message.setStatus(MsgStatusEnum.SUCCESS);
		switch (insuranceDetail.getStatus()) {
		  case "10":
			message.setInsStatus(InsuranceStatusEnum.EFFECT);
			break;
		  case "14":
		  case "50":
			message.setInsStatus(InsuranceStatusEnum.CANCELED);
			break;
		  default:
			message.setInsStatus(InsuranceStatusEnum.INVALID);
			break;
		}
	  } else {
		message.setStatus(MsgStatusEnum.FAIL);
	  }
	} catch (Exception ex) {
	  ex.printStackTrace();
	  message.setMessage(ex.getMessage());
	  message.setStatus(MsgStatusEnum.FAIL);
	}
	return message;
  }

  @Override
  public InsReturnMsg PolicyCancel(OrderItemInfo info) {
	InsReturnMsg message = new InsReturnMsg();
	SoapBusinessInterServiceLocator sbic = new SoapBusinessInterServiceLocator();
	PolicyCancelRequest request = new PolicyCancelRequest();
	PolicyCancelResponse response = new PolicyCancelResponse();
	WssUserInfo wui = new WssUserInfo();
	request.setPolicyNo(info.getInsuranceNo());
	request.setUserInfo(getUserInfo());

	logger.info("CPIC_Cancel_Request:" + info.getInsuranceNo());

	try {
	  response = sbic.getSoapApplyBusiness().policyCancel(request);

	  logger.info("CPIC_Cancel_Response:"
		  + response.getSysMessage().getNoteMsg());

	  message.setMessage(response.getSysMessage().getNoteMsg()
		  + response.getSysMessage().getErrorMsg());

	  if (response.getSysMessage().getReturnNumber().equals(SUCCESSFULLY_CODE)) {
		message.setStatus(MsgStatusEnum.SUCCESS);
		message.setInsStatus(InsuranceStatusEnum.CANCELED);
	  } else {
		message.setStatus(MsgStatusEnum.FAIL);
	  }
	} catch (Exception e) {
	  // TODO Auto-generated catch block
	  e.printStackTrace();
	  message.setMessage(e.getMessage());
	  message.setStatus(MsgStatusEnum.FAIL);
	}
	return message;
  }

  public String getProductCode() {
	return productCode;
  }

  public void setProductCode(String productCode) {
	this.productCode = productCode;
  }

  public CPICConfigAir getCpicConfigAir() {
	ConfigManagementAir config = new ConfigManagementAir(productCode);
	return config.getCPICConfiguration();
  }

  // / <summary>
  // / 获取证件类型
  // / </summary>
  // / <param name="certificateType"></param>
  // / <returns></returns>
  private String getCertificateType(String certificateType) {
	if (certificateType.equals("身份证")) {
	  return "0";
	} else if (certificateType.equals("军人证")) {
	  return "1";
	} else if (certificateType.equals("护照")) {
	  return "2";
	} else if (certificateType.equals("驾照")) {
	  return "3";
	} else {
	  return "4";
	}
  }

  private String getGender(String gender) {
	String g = "1";
	if (gender.equals("女")) {
	  g = "2";
	}
	return g;
  }

  private WssUserInfo getUserInfo() {
	WssUserInfo info = new WssUserInfo();
	// info.loginName = "guda";
	// info.password = "guda@2010";
	// info.orgId = 0x5bcd13;//6016275
	// info.loginName = "BJLK";
	// info.password = "1q2w3e";
	// info.orgId = 0x6e1ff7;//7217143
	info.setLoginName(cpicConfigAir.getLoginName());
	info.setPassword(cpicConfigAir.getPwd());
	info.setOrgId(cpicConfigAir.getOrgId());
	return info;
  }
}
